package com.example.administrator.seppdzxing;

import android.content.Context;
import android.graphics.Rect;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.View;
import android.widget.RelativeLayout;

import com.example.administrator.seppdzxing.camera.CameraManager;
import com.example.administrator.seppdzxing.decode.DecodeThread;
import com.example.administrator.seppdzxing.listener.ScanResultLisinter;
import com.example.administrator.seppdzxing.utils.CaptureActivityHandler;
import com.google.zxing.Result;

import java.util.Collection;


class QrCodeView extends RelativeLayout implements ICaptureView ,SurfaceHolder.Callback{
    protected CameraManager cameraManager;
    protected CaptureActivityHandler handler;
    protected IScanBoxView scanCropView;
    protected Rect mCropRect;
    protected ScanResultLisinter scanListener;
    private MySufaceView scanPreview;
    private boolean isHasSurface = false;
    private boolean isSport;
    private boolean stop;

    public QrCodeView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context,attrs);
    }
    private void init(Context context, AttributeSet attrs) {
        scanPreview = new MySufaceView(context,attrs);
        addView(scanPreview);
        scanCropView = new ScanBoxView(context,attrs);
        LayoutParams layoutParams = new LayoutParams(context, attrs);
        layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
        addView((View) scanCropView,layoutParams);
    }

    public void setScanListener(ScanResultLisinter scanListener){
        this.scanListener = scanListener;
    }

    public void onResume(boolean stop){
        this.stop = stop;

        cameraManager = new CameraManager(getContext());
        if (isHasSurface) {
            initCamera(scanPreview.getHolder());
        } else {
            scanPreview.getHolder().addCallback(this);

        }
    }

    public ScanBoxView getScanBoxView(){
        return (ScanBoxView) scanCropView;
    }

    public void onPause(){
        if (!isHasSurface) {
            scanPreview.getHolder().removeCallback(this);
        }
    }

    public void onStop() {
        stopSport();

        if(cameraManager!=null){
            cameraManager.closeDriver();

        }

    }

    public void onDestroy() {
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
            scanListener = null;
        }

    }

    private void initCamera(final SurfaceHolder surfaceHolder) {
        if (surfaceHolder == null) {
            throw new IllegalStateException("No SurfaceHolder provided");
        }
        if (cameraManager.isOpen()) {
            return;
        }
        try {
            cameraManager.openDriver(surfaceHolder);
            if (handler == null) {
                handler = new CaptureActivityHandler(QrCodeView.this, cameraManager, DecodeThread.ALL_MODE);
            }else {
                handler.setCameraManager(cameraManager);
            }
            if(stop){
                handler.stopeStoprt();
            }else {
                handler.starStoprt();
            }
            initCrop();
        } catch (Exception ioe) {
            if(scanListener!=null){
                scanListener.openCameraError();
            }
        }
    }

    /**
     * 继续扫描
     */
    public void restartSport(){
        if(handler!=null){
            handler.starStoprt();
        }
    }

    /**
     * 暂停识别
     */
    public void stopSport(){
        if(handler!=null){
            handler.stopeStoprt();
        }
    }

    /**
     * decodeBitmap
     * @param picturePath
     */
    public void decodeBitmap(String picturePath){
        if(cameraManager == null){
            cameraManager = new CameraManager(getContext());
        }
        if(handler==null){
            handler = new CaptureActivityHandler(this, cameraManager, DecodeThread.ALL_MODE);
        }
        handler.decodeBitmap(picturePath);
    }


    /**
     * 初始化截取的矩形区域
     */
    private void initCrop() {
        int cameraWidth = cameraManager.getCameraResolution().y;
        int cameraHeight = cameraManager.getCameraResolution().x;

        Rect rect = scanCropView.getmFramingRect();
        int cropLeft = rect.left;
        int cropTop = rect.top ;
        int cropWidth = rect.width();
        int cropHeight = rect.height();
        int containerWidth = getWidth();
        int containerHeight = getHeight();
        int x = cropLeft * cameraWidth / containerWidth;
        int y = cropTop * cameraHeight / containerHeight;
        int width = cropWidth * cameraWidth / containerWidth;
        int height = cropHeight * cameraHeight / containerHeight;
        mCropRect = new Rect(x, y, width + x, height + y);
    }

    @Override
    public CameraManager getCameraManager() {
        return cameraManager;
    }

    @Override
    public Rect getCropRect() {
        return mCropRect;
    }

    @Override
    public Handler getScanHandler(){
        return handler;
    }

    @Override
    public void handleDecode(Result result, Bundle bundle) {
       if(scanListener!=null){
           scanListener.handleDecode(result,bundle);
       }
    }

    @Override
    public void handleDecodeBitmapError() {
        if(scanListener!=null){
            scanListener.handleDecodeBitmapError();
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!isHasSurface) {
            isHasSurface = true;
            initCamera(holder);
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int measuredWidth, int measuredHeight) {
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        isHasSurface = false;
    }

    /**
     * 关闭闪光灯
     */
    public void closeFlashlight() {
        if(cameraManager!=null){
            doSetTorch(cameraManager.getCamera(), false);
        }
    }

    public void openFlashlight() {
        if(cameraManager!=null){
            doSetTorch(cameraManager.getCamera(), true);
        }
    }

    private void doSetTorch(Camera camera, boolean newSetting) {
        if(camera==null){
            return;
        }
        Camera.Parameters parameters = camera.getParameters();
        String flashMode;
        /** 是否支持闪光灯 */
        if (newSetting) {
            flashMode = findSettableValue(parameters.getSupportedFlashModes(), Camera.Parameters.FLASH_MODE_TORCH, Camera.Parameters.FLASH_MODE_ON);
        } else {
            flashMode = findSettableValue(parameters.getSupportedFlashModes(), Camera.Parameters.FLASH_MODE_OFF);
        }
        if (flashMode != null) {
            parameters.setFlashMode(flashMode);
        }
        camera.setParameters(parameters);
    }
    private static String findSettableValue(Collection<String> supportedValues, String... desiredValues) {
        String result = null;
        if (supportedValues != null) {
            for (String desiredValue : desiredValues) {
                if (supportedValues.contains(desiredValue)) {
                    result = desiredValue;
                    break;
                }
            }
        }
        return result;
    }


}
